from rest_framework import status
from rest_framework.generics import CreateAPIView, GenericAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated

from .models import User
from .serializers import CreateUserSerializer,UserDetailSerializer,EmailSerializer
from rest_framework.views import APIView


# class UserView(GenericAPIView):
#     """用戶註冊"""
#     serializer_class = CreateUserSerializer
#
#     def post(self,request):
#
#         serializer = self.get_serializer(data = request.data)
#         serializer.is_valid(raise_exception = True)
#         serializer.save()
#         return Response(serializer.data,status = status.HTTP_201_CREATED)
#
# class CreateAPIView(mixins.CreateModelMixin,
#                     GenericAPIView):
#     """
#     Concrete view for creating a model instance.
#     """
#     def post(self, request, *args, **kwargs):
#         serializer = self.get_serializer(data=request.data)
#         serializer.is_valid(raise_exception=True)
#         self.perform_create(serializer)
#         headers = self.get_success_headers(serializer.data)
#         serializer.save()
#         return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

class UserView(CreateAPIView):
    """用戶註冊"""
    serializer_class = CreateUserSerializer

class UserCountView(APIView):
    """判斷用戶名是否已註冊"""
    def get(self,request,username):
        # 查詢user表
        count = User.objects.filter(username=username).count()

        # 包裝響應數據
        data={
            'username':username,
            'count':count,
        }
        # 數據
        return Response(data)

class MobileCountView(APIView):
    """判斷手機號是否已註冊"""
    def get(self,request,mobile):
        # 查詢數據庫
        count = User.objects.filter(mobile = mobile).count()
        # 構造響應數據
        data = {
            'mobile':mobile,
            'count':count
        }
        # 響應
        return Response(data)

# GET /user/
class UserDetailView(RetrieveAPIView):
    """用户详细信息展示"""
    serializer_class = UserDetailSerializer
    # queryset = User.objects.all()
    permission_classes = [IsAuthenticated] # 指定权限只有通过认证的用户才能访问当前视图

    def get_object(self):
        """重写此方法返回 要展示的用户模型对象"""
        return self.request.user

# PUT /email/
class EmailView(UpdateAPIView):
    serializer_class = EmailSerializer
    permission_classes = [IsAuthenticated]


    def get_object(self):
        return self.request.user

class EmailVerifyView(APIView):
    """激活用户邮箱"""

    def get(self,request):
        # 获取前端查询字符串中传入的token
        token = request.query_params.get('token')
        # 把token解密 并查询对应的user
        user = User.check_email_verify_token(token)
        # 修改当前user的email_active为true
        if user is None:
            return Response({'message':'激活失败'},status=status.HTTP_400_BAD_REQUEST)
        user.email_active = True
        user.save()
        # 响应
        return Response({'message':'ok'})